import type { FC, ReactNode } from 'react'
import React, { memo, useEffect, useState } from 'react'
import type { SelectProps } from 'antd'
import { Select } from 'antd'
import { useMySelector } from '@/store'
import { decryptData } from '@/utils/encrypt'
import { getSelectUserData } from '@/service/module/main/sign/daily-attendance'

interface IProps {
  children?: ReactNode
  getUserId?: (id: number) => void
}

const SearchInput: FC<IProps> = (props) => {
  const [options, setOptions] = useState<SelectProps['options']>([])
  const [value, setValue] = useState<any>(undefined)
  const { privateKey } = useMySelector((state) => ({
    privateKey: state.app.privateKey
  }))

  // 获取下拉框数据
  const getOptions = async (userName = '') => {
    const res = await getSelectUserData(userName)
    const newData = decryptData(privateKey, res.data)
    setOptions(newData)
  }
  useEffect(() => {
    getOptions()
  }, [])

  const handleSearch = async (newValue: string) => {
    getOptions(newValue)
  }

  const handleChange = (newValue: number) => {
    props.getUserId?.(newValue)
    setValue(newValue)
  }

  return (
    <Select
      showSearch
      value={value}
      placeholder={'输入您要搜索的用户'}
      style={{ width: '100%' }}
      defaultActiveFirstOption={true}
      showArrow={false}
      filterOption={false}
      onSearch={handleSearch}
      onChange={handleChange}
      notFoundContent={null}
      options={options}
    />
  )
}

export default memo(SearchInput)
